<template>
  <Upload :multiple="multiple" :fileList="fileList" :previewFile="previewFile"
          :class="['h-flow-uploader', {'h-flow-uploader-disaled': disabled }]"
          @change="handleChange" :action="action" :headers="request.headers">
    <Button v-if="!disabled">
      <Icon type="upload"/>
      {{ buttonName }}
    </Button>
  </Upload>
</template>
<script>
import {Button, Icon, Modal, Upload} from "ant-design-vue";
import {createModelProps, createProps, isEmpty} from '@/utils';
import {createService} from '@/request/service';

export default {
  components: {Modal, Button, Icon, Upload},
  model: createModelProps(),
  props: {
    disabled: createProps(Boolean),
    multiple: createProps(Boolean, true),
    value: createProps(String),
    attachMentTyp: createProps(String, 'comment'),
    buttonName: createProps(String, '上传'),
    request: createProps(Object, () => ({
      baseURL: '/h-flow',
      headers: {},
    }))
  },
  data() {
    return {
      fileList: [],
      previewVisible: false,
      previewImage: '',
      uploading: false
    };
  },
  methods: {
    previewFile(file) {
      console.log(file);
    },
    handleChange({file, fileList}) {
      this.fileList = fileList;
      if (!this.multiple && this.fileList.length > 1) {
        this.fileList = [fileList[fileList.length - 1]];
      }
      this.resolveProperties(this.fileList);
      this.valueChange(this.fileList);

      this.uploading = !!this.fileList.find(f => f.status === 'uploading');
    },
    valueChange() {
      this.$emit('change', this.fileList.map(f => f.id).filter(f => !!f).toString());
    },
    resolveProperties(fileList) {
      fileList.forEach(item => {
        if (item.response && item.response.url) {
          this.copyProperties(item, item.response);
        }
      });
    },
    loadFiles() {
      if (this.uploading) return;
      if (isEmpty(this.value)) {
        this.fileList = [];
        return;
      }
      createService(this.request).post('/flow/loadAttachments', {ids: this.value}).then(files => {
        this.fileList = files.map(f => {
          let item = this.copyProperties({}, f);
          item.uid = item.id;
          return item;
        });
      });
    },
    copyProperties(item, attachment) {
      item.id = attachment.id;
      item.name = attachment.fileName;
      item.percent = 100;
      item.size = attachment.fileSize;
      item.status = 'done';
      item.type = attachment.ext;
      item.url = this.request.baseURL + attachment.url;
      return item;
    },
  },
  watch: {
    value: {
      handler() {
        this.loadFiles();
      },
      immediate: true
    }
  },
  computed: {
    action() {
      return this.request.baseURL + `/flow/upload?attachMentType=${this.attachMentTyp}`;
    },
  }
};
</script>


<style>
.h-flow-uploader-disaled .ant-upload-list-item-card-actions {
  display: none;
}
</style>
